#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ROOT_DIR="$(dirname "$(dirname "$SCRIPT_DIR")")"

WORK_DIR="$SCRIPT_DIR/work"
LOCALES_DIR="$ROOT_DIR/chrome/locale"

rm -rf "$WORK_DIR"
mkdir "$WORK_DIR"
cd $WORK_DIR
# Create temporary directories for merge script
mkdir en-US-new locales content-locales output
cp -R $LOCALES_DIR/en-US/zotero/* en-US-new
cp -R $LOCALES_DIR/ locales/
rm -rf locales/en-US
# Correct various errors
find locales -name '*.dtd' -exec perl -pi -e "s/&amp;([^\s])/&\$1/g" {} \;
find locales -name '*.properties' -exec rpl 'S%' '%S' {} \;
find locales -name '*.properties' -exec rpl '/n' '\n' {} \;
find locales -name '*.properties' -exec rpl '\\' '\' {} \;
find locales -name '*.properties' -exec rpl '\n\n\(?!n)' '\n\n' {} \;
find locales -name '*.properties' -exec rpl '\\' '\' {} \;

# Run merge script
$SCRIPT_DIR/localizer
rsync -a --progress --verbose $WORK_DIR/output/locale/ $LOCALES_DIR/

rpl -R ⏎ '\n' "$LOCALES_DIR"

rm -rf en-US-new locales content-locales output

$SCRIPT_DIR/filter_connector_json "$LOCALES_DIR"

cd "$ROOT_DIR/resource/schema/global"
./scripts/update-schema
